package com.whu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whu.domain.User;
import com.whu.mapper.UserMapper;
import com.whu.service.UserService;
import com.whu.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;

/**
 * @author Dd
 * @date 2020/11/12 - 20:05
 */
@Slf4j
@RestController
@RequestMapping("/login")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;


    //注册用户
    @RequestMapping("/register")
   public JsonUtil insertUser(@RequestBody User user){
        JsonUtil json = new JsonUtil();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("name",user.getName());
        wrapper.eq("password",user.getPassword());
        List<User> users = userMapper.selectList(wrapper);
        if(users.isEmpty()){
            int insert = userMapper.insert(user);
            json.setResCode(1);
            HashMap<String, Object> hmap = new HashMap<>();
            hmap.put("data","无");
            hmap.put("msg","注册成功");
            return json;
        }
        else {
            json.setResCode(-1);
            HashMap<String, Object> hmap = new HashMap<>();
            hmap.put("data","无");
            hmap.put("msg","注册失败，请重新注册");
            return json;
        }
    }
    //用户登录
    @RequestMapping("/login")
    public JsonUtil loginUser(@RequestBody User user){
        JsonUtil json = new JsonUtil();
        HashMap<String, Object> maps = new HashMap<>();
        maps.put("name",user.getName());
        maps.put("password",user.getPassword());
        List<User> users = userMapper.selectByMap(maps);
        if (users.isEmpty())
        {
            json.setResCode(-1);
            HashMap<String, Object> hmap = new HashMap<>();
            hmap.put("msg","账号或密码错误");
            hmap.put("data","无");
            json.setMaps(hmap);
            return json;
        }
        else {
            json.setResCode(0);
            HashMap<String, Object> hmap = new HashMap<>();
            hmap.put("msg","登录成功");
            hmap.put("data",user);
            return json;
        }

    }

}
